<?php

class AttributeController extends Controller {

    public function indexAction() {
        $goodsType = Factory::M("GoodsTypeModel");
        $types = $goodsType->getGoodsTypes();
        $type_id = $_GET['type_id'] + 0;
        $attrModel = Factory::M("AttributeModel");
        $current = isset($_GET['page']) ? $_GET['page'] : 1;
        $pagesize = 10;
        $offset = ($current - 1) * $pagesize;
        $where = ($type_id == 0) ? "" : "type_id = $type_id";
        $total = $attrModel->total($where);
        $page = new Page($total, $pagesize, $current, 'index.php',
            array('p' => 'back', 'c' => 'attribute', 'a' => 'index', 'type_id' => $type_id));
        $pageinfo = $page->showPage();
        $attrs = $attrModel->getPageAttrs($type_id, $offset, $pagesize);
        include CURRENT_VIEW_PATH . 'attribute_list.html';
    }

    public function addAction() {
        $goodsType = Factory::M("GoodsTypeModel");
        $types = $goodsType->getGoodsTypes();
        include CURRENT_VIEW_PATH . 'attribute_add.html';
    }

    public function insertAction() {
        $data = array();
        $data['attr_name'] = trim($_POST['attr_name']);
        $data['type_id'] = $_POST['type_id'];
        $data['attr_type'] = $_POST['attr_type'];
        $data['attr_input_type'] = $_POST['attr_input_type'];
        $data['attr_value'] = isset($_POST['attr_value']) ? $_POST['attr_value'] : "";

        //判断数据可用性
        if(empty($data['attr_name'])) {
            $this->_jump("index.php?p=back&c=attribute&a=add", "属性名称不能为空", 2);
        }

        if($data['type_id'] == 0) {
            $this->_jump("index.php?p=back&c=attribute&a=add", "请选择所属商品类型", 2);
        }

        //提交数据
        $attributeModel = Factory::M("AttributeModel");
        if($attributeModel->insert($data)) {
            $this->_jump("index.php?p=back&c=attribute&a=index&type_id={$data['type_id']}");
        }
        else {
            $this->_jump("index.php?p=back&c=attribute&a=add", "属性添加失败");
        }
    }

}